import { ref } from 'vue';
import { ElMessageBox } from 'element-plus';
import { downloadNewFile } from '@/utils/publicUtils';

export default function useImportExport() {
	let importDrawer = ref({ isShow: false });

	function isEmpty(obj) {
		return Object.keys(obj).length === 0;
	}

	// 打开导入抽屉
	function handleOpenImportDrawer() {
		importDrawer.value.isShow = true;
	}

	// 导入文件
	function importFile(params, importApi, projectCode, cb) {
		let param = new FormData();
		params.forEach(el => {
			param.append('file', el.file);
		});
		param.append('projectCode', projectCode);
		importApi(param).then(res => {
			if (res.data.code == 200) {
				// 导入成功，显示结果并关闭抽屉
				ElMessageBox.alert(res.data.data, '导入结果', {
					dangerouslyUseHTMLString: true,
				});
				importDrawer.value.isShow = false;
				cb && cb();
			}
		});
	}

	// 处理下载
	function handleDownload(query = {}, exportApi, name) {
		let fileName = isEmpty(query) ? name + '导入模板.xlsx' : name + '数据.xlsx';
		if (query.pageSize) query.pageSize = 5000;
		exportApi(query).then(res => {
			downloadNewFile(res.data, fileName);
		});
	}

	// 关闭导入抽屉
	function closeImportDrawer() {
		importDrawer.value.isShow = false;
	}

	return {
		importDrawer,
		handleOpenImportDrawer,
		importFile,
		handleDownload,
		closeImportDrawer,
	};
}
